package com.youlu.campus.service.activity;

import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.ActivityInfo;
import com.youlu.campus.entity.ActivityQaInfo;
import com.youlu.campus.entity.ActivityRewardRule;
import com.youlu.campus.entity.ActivityTaskInfo;
import com.youlu.campus.entity.UserInfoExtend;
import com.youlu.campus.entity.UserPO;
import com.youlu.campus.entity.UserParticipateActivityInfo;
import com.youlu.campus.entity.VO.res.ActivityDetailMiniContestRes;
import com.youlu.campus.entity.VO.res.UserCaHonorRes;
import com.youlu.campus.entity.VO.res.UserInviteDetailRes;
import com.youlu.campus.entity.VO.res.UserSignInRes;
import com.youlu.campus.entity.ca.UserCa;
import com.youlu.campus.entity.course.entity.CourseSimpleActivityEntity;
import com.youlu.campus.entity.course.vo.ActivityResultVo;
import com.youlu.campus.entity.english.vo.response.CompetitionUserInviteResponse;
import com.youlu.campus.entity.enums.TaskBizType;
import com.youlu.campus.entity.timetable.UserTimetableConfig;
import com.youlu.campus.service.ca.UserCaService;
import com.youlu.campus.service.ca.impl.CaCertificateConfigService;
import com.youlu.campus.service.contest.QQMiniContestService;
import com.youlu.campus.service.course.convert.LiteHomeCourseConvert;
import com.youlu.campus.service.english.CompetitionUserInviteService;
import com.youlu.campus.service.invite.UserInviteRecordService;
import com.youlu.campus.service.qa.ActivityQaInfoService;
import com.youlu.campus.service.timetable.UserTimetableConfigService;
import com.youlu.campus.service.universitytimetable.UserSignInService;
import com.youlu.campus.service.visitor.UserInfoExtendService;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Slf4j
@Service
public class WxMiniContestActivityService {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private ActivityTaskService activityTaskService;

    @Autowired
    private QQMiniContestService qqMiniContestService;

    @Autowired
    private UserParticipateActivityInfoService userParticipateActivityInfoService;

    @Autowired
    private UserCaService userCaService;

    @Autowired
    private UserInviteRecordService userInviteRecordService;

    @Autowired
    private CaCertificateConfigService caCertificateConfigService;

    @Autowired
    private ActivityRewardRuleService activityRewardRuleService;

    @Autowired
    private UserInfoExtendService userInfoExtendService;

    @Autowired
    private ActivityQaInfoService activityQaInfoService;

    @Autowired
    private CompetitionUserInviteService competitionUserInviteService;

    @Autowired
    private UserSignInService userSignInService;

    @Autowired
    private UserTimetableConfigService userTimetableConfigService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private LiteHomeCourseConvert liteHomeCourseConvert;

    @Autowired
    private MapperFacade mapperFacade;


    public UserInviteDetailRes findByActivityId(UserPO currentUser, String activityId) {
        log.info("【获取用户参与志愿者信息】activityId->{}| userId ->{}", activityId, currentUser);
        ActivityInfo activityInfo = activityService.findOne(activityId);
        UserInviteDetailRes userInviteDetailRes = new UserInviteDetailRes();
        userInviteDetailRes.setWxMiniOfficialQrcode(activityInfo.getWxMiniOfficialQrcode());
        userInviteDetailRes.setCsDesc(activityInfo.getCsDesc());
        userInviteDetailRes.setHasElectronicCa(activityInfo.getHasElectronicCa());
        userInviteDetailRes.setHasPaperCa(activityInfo.getHasPaperCa());
        userInviteDetailRes.setActivityType(activityInfo.getType());
        ActivityTaskInfo activityTaskInfo = activityTaskService.find(activityId, TaskBizType.INVITE);
        if (Objects.isNull(activityTaskInfo)) {
            throw new BusinessException("未配置分享任务信息");
        }
        userInviteDetailRes.setTaskId(activityTaskInfo.getId());
        if (Objects.nonNull(activityTaskInfo) && activityTaskInfo.getShareInviteButtonType() == 2) {
            userInviteDetailRes.setInviteImageButton(activityTaskInfo.getShareInviteButtonBackGroundImgUrl());
        }
        if (MapUtils.isEmpty(activityInfo.getCaMatchKeyWords())) {
            throw new BusinessException("证书领取关键字信息未配置");
        }
        if ("douyin".equals(activityInfo.getType())) {
            ActivityQaInfo activityQaInfo = activityQaInfoService.findByActivityIdAndQaNumber(activityId, 1);
            if (Objects.nonNull(activityQaInfo)) {
                userInviteDetailRes.setQaInfoId(activityQaInfo.getId());
            }
        }

        String inviteKeys = activityInfo.getCaMatchKeyWords().get("invite");
        //领取纸质版
        Integer receivePaperCaOfInviteCount = activityInfo.getReceivePaperCaOfInviteCount();
        CompetitionUserInviteResponse competitionUserInvite = new CompetitionUserInviteResponse();
        //获取邀请人数
        Integer inviteCount = userInviteRecordService.getInviteUserCount(currentUser.getId(), activityId,
                activityTaskInfo.getId(), Boolean.TRUE).intValue();
        if (inviteCount == 0) {
            if ("douyin".equals(activityInfo.getType())) {
                competitionUserInvite.setInviteValue(0);
                competitionUserInviteService.matchRule(activityTaskInfo, activityId, competitionUserInvite);
                userInviteDetailRes.setRate(competitionUserInvite.getRate());
                userInviteDetailRes.setTips(competitionUserInvite.getTips());
            }
            return userInviteDetailRes;
        }
        if ("douyin".equals(activityInfo.getType())) {
            competitionUserInvite.setInviteValue(inviteCount);
            competitionUserInviteService.matchRule(activityTaskInfo, activityId, competitionUserInvite);
            userInviteDetailRes.setRate(competitionUserInvite.getRate());
            userInviteDetailRes.setTips(competitionUserInvite.getTips());
        }

        List<UserCaHonorRes> list = caCertificateConfigService.findByActivityId(activityId);
        if (CollectionUtils.isEmpty(list)) {
            return userInviteDetailRes;
        }
        long count = list.stream().filter(userCaHonorRes -> userCaHonorRes.getCaType().equals(inviteKeys)).count();
        if (count == 0) {
            log.error("【获取用户参与志愿者信息】activityId->{}| userId ->{} 未找到相关证书配置 inviteKey ->{}", activityId,
                    currentUser, inviteKeys);
            throw new BusinessException("证书领取关键字信息未匹配到");
        }
        List<ActivityRewardRule> activityRewardRuleList = activityRewardRuleService.findByActivityId(activityId);
        if (CollectionUtils.isEmpty(activityRewardRuleList)) {
            return userInviteDetailRes;
        }
        UserInfoExtend userInfoExtend = userInfoExtendService.findByUserIdAndAppId(currentUser);
        if (Objects.isNull(userInfoExtend)) {
            userInfoExtend = new UserInfoExtend();
        }
        UserInfoExtend finalUserInfoExtend = userInfoExtend;
        for (ActivityRewardRule activityRewardRule : activityRewardRuleList) {
            Optional<UserCaHonorRes> userCaHonorOptional =
                    list.stream().filter(userCaHonorRes -> userCaHonorRes.getCaLevel().equals(activityRewardRule.getCaName())).findFirst();
            if (userCaHonorOptional.isPresent()) {
                UserCaHonorRes userCaHonorRes = userCaHonorOptional.get();
                userCaHonorRes.setSort(activityRewardRule.getPriority());
                switch (activityRewardRule.getInviteOperatorType()) {
                    case "section":
                        if (inviteCount >= activityRewardRule.getInviteStart().intValue()) {
                            userCaHonorRes.setCaReceivedLock(Boolean.TRUE);
                            log.info("【获取用户参与志愿者信息】activityId->{}| userId ->{} 已匹配规则(section) ->{} 等级->{} ", activityId,
                                    currentUser, inviteCount, activityRewardRule.getCaName());
                        }
                        break;
                    case "rightInterval":
                        if (inviteCount >= activityRewardRule.getInviteEnd().intValue()) {
                            userCaHonorRes.setCaReceivedLock(Boolean.TRUE);
                            log.info("【获取用户参与志愿者信息】activityId->{}| userId ->{} 已匹配规则(rightInterval) ->{} 等级->{} ",
                                    activityId,
                                    currentUser, inviteCount, activityRewardRule.getCaName());
                        }
                        break;
                    case "equals":
                        if (inviteCount.equals(activityRewardRule.getInviteEqu().intValue())) {
                            userCaHonorRes.setCaReceivedLock(Boolean.TRUE);
                            log.info("【获取用户参与志愿者信息】activityId->{}| userId ->{} 已匹配规则(equals) ->{} 等级->{} ", activityId,
                                    currentUser, inviteCount, activityRewardRule.getCaName());
                        }
                        break;
                    default:
                }
                if (userCaHonorRes.getCaReceivedLock() && (receivePaperCaOfInviteCount > 0 && inviteCount >= receivePaperCaOfInviteCount)) {
                    log.info("【获取用户参与志愿者信息】activityId->{}| userId ->{} 已满足领取纸质版 等级->{} ", activityId,
                            currentUser, activityRewardRule.getCaName());
                    userInviteDetailRes.setPaperCaReceive(Boolean.TRUE);
                }
                if (userCaHonorRes.getCaReceivedLock()) {
                    userInviteDetailRes.setDigitalCaReceive(Boolean.TRUE);
                    UserCa userCa = new UserCa();
                    userCa.setUserId(currentUser.getId());
                    userCa.setTaskBizType("invite");
                    userCa.setUniversityId(finalUserInfoExtend.getUniversityId());
                    userCa.setUniversityName(finalUserInfoExtend.getUniversityName());
                    userCa.setName(finalUserInfoExtend.getName());
                    userCa.setMobile(finalUserInfoExtend.getMobile());
                    userCa.setCaType(userCaHonorRes.getCaType());
                    userCa.setActivityId(activityId);
                    userCa.setCaLevel(userCaHonorRes.getCaLevel());
                    userCa.setGrade(finalUserInfoExtend.getGrade());
                    userCa.setPlatform(finalUserInfoExtend.getPlatform());
                    userCa.setAppId(finalUserInfoExtend.getAppId());
                    userCa.setPlatform(currentUser.getCurrentPlatform());
                    userCa.setAppId(currentUser.getAppId());
                    userCa.setCertificateActivityConfigId(userCaHonorRes.getCertificateActivityConfigId());
                    userCaService.create(userCa);
                    userInviteDetailRes.setCaType(userCaHonorRes.getCaType());
                    userInviteDetailRes.setCaLevel(userCaHonorRes.getCaLevel());
                    break;
                }
            }
        }

        return userInviteDetailRes;
    }


    public ActivityDetailMiniContestRes findDetailByActivityId(String activityId, UserPO currentUser) {
        ActivityInfo activityInfo = activityService.findOne(activityId);
        if (Objects.isNull(activityInfo)) {
            throw new BusinessException("活动不存在");
        }
        ActivityDetailMiniContestRes activityDetailMiniContest = new ActivityDetailMiniContestRes();
        activityDetailMiniContest.setDetail(activityInfo.getDetail());
        activityDetailMiniContest.setStop(activityInfo.getStop());
        activityDetailMiniContest.setStopDetail(activityInfo.getStopDetail());
        activityDetailMiniContest.setThemeColor(activityInfo.getThemeColor());
        activityDetailMiniContest.setActivityType(activityInfo.getType());
        activityDetailMiniContest.setQaMode(activityInfo.getQaMode());
        activityDetailMiniContest.setHasVolunteerInvite(activityInfo.getHasVolunteerInvite());
        activityDetailMiniContest.setStatus(qqMiniContestService.getActivityStatus(activityInfo.getEndTime()));
        activityDetailMiniContest.setRecieveCaDetail(activityInfo.getRecieveCaDetail());
        if (Objects.nonNull(currentUser)) {
            UserParticipateActivityInfo user =
                    userParticipateActivityInfoService.findByUserIdActivityId(currentUser.getId(), activityId);
            if (Objects.nonNull(user)) {
                activityDetailMiniContest.setJoined(Boolean.TRUE);
            }
        }
        ActivityTaskInfo activityTaskInfo = activityTaskService.find(activityId, TaskBizType.INVITE);
        if(Objects.nonNull(activityTaskInfo)){
            activityDetailMiniContest.setTaskId(activityTaskInfo.getId());
        }

        String type = activityInfo.getType();
        if("daka".equals(type)||"timetable".equals(type)){
            UserSignInRes userSignInfo = userSignInService.getUserSignInfo(currentUser, activityId);
            BeanUtils.copyProperties(userSignInfo,activityDetailMiniContest);
            if("timetable".equals(type)){
                UserTimetableConfig userConfig = userTimetableConfigService.getUserConfig(activityId, currentUser.getId());
                if(Objects.nonNull(userConfig)){
                    activityDetailMiniContest.setStartDateStr(userConfig.getStartDateStr());
                }
                CourseSimpleActivityEntity courseSimpleActivityEntity = mongoTemplate.findById(activityId, CourseSimpleActivityEntity.class);
                if(Objects.nonNull(courseSimpleActivityEntity)){
                    activityDetailMiniContest.setActivityResult(liteHomeCourseConvert.updateJoinNum(courseSimpleActivityEntity,
                            mapperFacade.map(courseSimpleActivityEntity, ActivityResultVo.class), Boolean.FALSE));
                }
            }
        }
        return activityDetailMiniContest;
    }


}
